<template>
  <div class="article_container">
    <van-nav-bar
      @click-left="$router.back()"
      left-arrow
      title="文章详情"
    />

    <!-- <article-detail :article="article" />
    <article-comment
      :commentList="commentList"
      :toBottom="toBottom"
    /> -->

    <van-list
      :finished="finished"
      @load="onLoad"
      finished-text="没有更多了"
      v-model="loading"
    >
      <article-detail :article="article" />
      <article-comment
        :commentList="commentList"
      />
    </van-list>

    <article-bar
      :article="article"
      :comCount="comCount"
    />
  </div>
</template>

<script>
import ArticleDetail from "./chi-coms/article-detail";
import ArticleComment from "./chi-coms/article-comment/article-comment";
import ArticleBar from "./chi-coms/article-bar";

import { getArticleById, getComments } from "../../network/article";

export default {
  name: "Article",
  props: ["articleId"],
  components: {
    ArticleDetail,
    ArticleComment,
    ArticleBar
  },
  computed: {},
  data() {
    return {
      article: {},
      comCount: 0,
      offset: null,
      commentList: [],
      finished: false,
      loading:false
    };
  },
  created() {
    this.loadCurrentActicleDetail();
    // this.loadCurrentComment();
    //监听发送评论事件
    this.$bus.$on("addComment",res => {
      res.is_liking = false
      this.commentList.unshift(res)
      this.comCount++
    })
  },
  mounted() {},
  methods: {
    //应该在父组件获取文章详情，传递给子组件
    //获取文章详情
    async loadCurrentActicleDetail() {
      const result = await getArticleById(this.articleId);
      if (result.message !== "OK") {
        this.$toast.fail("该文章不存在");
        this.$router.back(-1);
      } else {
        // console.log(result);
        this.article = result.data;
      }
    },
    //获取文章评论
    async loadCurrentComment() {
      const result = await getComments({
        type: "a", // 评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
        source: this.articleId, // 源id，文章id或评论id
        offset: this.offset, // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
        limit: 10 // 每页大小
      });
      // console.log(result);
      if (result.message === "OK") {
        this.commentList = [...this.commentList, ...result.data.results];
        
        this.comCount = result.data.total_count;
        this.loading = false
        if (result.data.results.length) {
          
          this.offset = result.data.last_id;
        }else{
          this.finished = true;
        }
      } else {
        console.log("获取文章评论失败");
        this.finished = true
      }
    },

    onLoad() {
      this.loadCurrentComment()
    }
  }
};
</script>

<style scoped lang="stylus" >
@import url('./github-markdown.css')

.article_container
  height calc(100vh - 90px)
  overflow scroll
  background #fff
  padding-top 46px
  padding-bottom 44px

.van-nav-bar
  position fixed
  left 0
  right 0
  top 0
  height 46px
</style>